package com.my.study.util;

import com.alibaba.fastjson.JSON;
import com.my.study.entity.vo.ResponseVO;
import com.my.study.enums.BusinessExceptionEnum;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

public class HttpGlobalUtil {

    private static final String LOGIN = "login";

    /**
     * 失败返回值
     *
     * @param response
     * @param code
     * @return
     */
    public static Mono<Void> fail(ServerHttpResponse response, String code) {
        BusinessExceptionEnum businessExceptionEnum = BusinessExceptionEnum.getBusinessExceptionEnum(code);
        ResponseVO responseVO = ResponseVO.fail(Integer.valueOf(businessExceptionEnum.code), businessExceptionEnum.msg);
        byte[] bits = JSON.toJSONBytes(responseVO);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 失败返回值
     *
     * @param response
     * @return
     */
    public static Mono<Void> fail(ServerHttpResponse response) {
        ResponseVO responseVO = ResponseVO.fail(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        byte[] bits = JSON.toJSONBytes(responseVO);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 成功
     *
     * @param response
     * @return
     */
    public static Mono<Void> success(ServerHttpResponse response) {
        ResponseVO responseVO = ResponseVO.success();
        byte[] bits = JSON.toJSONBytes(responseVO);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
